package com.mz.ozy.utils;

import android.content.Context;
import android.widget.TextView;

import com.mz.ozy.R;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;


/**
 * Created by dengzh on 2018/4/9.
 * 验证码帮助类
 */

public class CodeHelper {

    private Context mContext;
    private TextView codeBt;
    private Disposable mDisposable;

    /**
     * 构造函数
     * @param mContext 上下文
     * @param codeBt   验证码的button
     */
    public CodeHelper(Context mContext, TextView codeBt) {
        this.mContext = mContext;
        this.codeBt = codeBt;
    }

    /**
     * 开启倒计时
     */
    public void start(){
        //点击后，按钮不可点
        codeBt.setEnabled(false);
        mDisposable = Flowable.intervalRange(0,60,0,1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        codeBt.setText((60 - aLong) + mContext.getString(R.string.resend_after_xx_second));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //倒计时完毕置为可点击状态
                        codeBt.setEnabled(true);
                        codeBt.setText(R.string.get_code);
                    }
                })
                .subscribe();
    }

    /**
     * 请求失败，立即重置状态
     */
    public void reset(){

        if(mDisposable!=null){
            mDisposable.dispose();
        }

        codeBt.setEnabled(true);
        codeBt.setText(R.string.get_code);
      //  codeBt.setBackgroundResource(R.drawable.bg_bt_code);
    }

    /**
     * 界面销毁时 释放
     */
    public void stop(){
        if(mDisposable!=null){
            mDisposable.dispose();
        }
    }

}
